package org.airline.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.apache.commons.io.output.ByteArrayOutputStream;

/**
 * 
 * 项目名称：airline
 * 包   名  称：org.airline.utils
 * 类   名  称：GenerateCode.java
 * 类   描  述：验证码生成工具类
 * 创   建  人：黄伟钢
 * 创建时间：2011-12-1 下午08:30:16 
 */
public class GenerateCode {

	private ByteArrayInputStream image;
	private String codeStr;
	private static int WIDTH = 60;
	private static int HEIGHT = 20;
	private static String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

	private GenerateCode() {
		this.init() ;
	}

	public static GenerateCode Instance() {
		return new GenerateCode();
	}

	public void init() {
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB) ;
		Graphics g = image.getGraphics() ;
		Random random = new Random() ;
		// 背景颜色
		g.setColor(new Color(241, 248, 254)) ;
		g.fillRect(0, 0, WIDTH, HEIGHT) ;
		// 设定字体
		g.setFont(new Font("Times New Roman",Font.BOLD | Font.ITALIC,16)) ;
		// 随机产生155条干扰线
		g.setColor(getRandColor(160,200)) ; 
		for (int i = 0; i < 360; i ++) {
			int x = random.nextInt(WIDTH) ;
			int y = random.nextInt(HEIGHT) ;
			int x1 = random.nextInt(12) ;
			int y1 = random.nextInt(12) ;
			g.drawLine(x, y, x + x1, y + y1) ;
		}
		String rands = "" ;
		for (int i = 0; i < 4; i ++) {
			int rand = (int)(Math.random() * 62);
			char unitRand = chars.charAt(rand) ;
			rands += unitRand ;
			// 设置验证码颜色
			g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));   
			g.drawString(unitRand+"",13*i+6,16); 
		}
		this.codeStr = rands ;
		g.dispose() ;
		ByteArrayInputStream input = null ;
		ByteArrayOutputStream output = new ByteArrayOutputStream() ;
		try {
			ImageOutputStream imageOut = ImageIO.createImageOutputStream(output) ;
			ImageIO.write(image, "JPEG", imageOut) ;
			imageOut.close() ;
			input = new ByteArrayInputStream(output.toByteArray()) ;
		} catch (Exception e) {
			System.out.println("验证码产生出错！") ;
			e.printStackTrace();
		}
		this.image = input ;
		
	}

	//给定范围获得随机颜色
	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	public ByteArrayInputStream getImage() {
		return image;
	}

	public String getCodeStr() {
		return codeStr;
	}

}
